# -*- coding: utf-8 -*-

import os
import sys
import datetime
import pytz
import jinja2

from openerp import SUPERUSER_ID, models
from openerp.osv import fields
from openerp.osv import orm
from openerp.osv import osv

if hasattr(sys, 'frozen'):
    # When running on compiled windows binary, we don't have access to package loader.
    path = os.path.realpath(os.path.join(os.path.dirname(__file__), '..', 'views'))
    loader = jinja2.FileSystemLoader(path)
else:
    loader = jinja2.PackageLoader('openerp.addons.portal_channel', "report")

env = jinja2.Environment(loader=loader, autoescape=True)

#jinja2模版自定义过滤器
def strftime(str, fmt):
    dt = datetime.datetime.strptime(str, '%Y-%m-%d %H:%M:%S')
    dt = dt.replace(tzinfo=pytz.utc).astimezone(pytz.timezone('Asia/Shanghai'))
    return dt.strftime(fmt.encode('utf-8')).decode('utf-8')

env.filters['strftime'] = strftime

# 代理商render订单打印模板
class sale_order_lodop(osv.AbstractModel):
    """Model used to embed old style reports"""
    _name = 'report.agents_sale_order_lodop'
    _template = None
    _wrapped_report_class = None

    def render_html(self, cr, uid, ids, data=None, context=None):
        model = 'agents.order'
        report_obj = self.pool[model]
        order = report_obj.browse(cr, uid, ids, context=context)
        #如果订单不是草稿状态或待审核状态打印，则将打印状态修改为已打印
        if order.state not in ['draft', 'sent']:
            order.write({'print_state': True})
        note_lines = []
        if order.remarks:
            note_lines = order.remarks.split('\n')
        options = data or {}
        template = env.get_template("report_sale_order.html")
        return template.render({
            'order': order,
            'note_lines': note_lines,
            'debug': context,
            'options': options,
            })
        #return self.pool['report'].render(cr, uid, [], self._template, docargs, context=context)
